<?php
/**
 * Created by PhpStorm.
 * User: renbin
 * 功能: 处理用户银行卡号
 * Date: 2015/6/8
 * Time: 9:59
 */
namespace common\models\Service;
use common\models\CommonFunction;
use common\models\CommonVar;
use common\models\DAO\User;
use common\models\DAO\UserCharge;
use common\models\DAO\UserIdentity;
use common\models\LLpay\LLpayConfig;
use common\models\LLpay\LLpayWapConfig;
use common\models\LLpay\LLpayWapSubmit;
use common\models\Validate;
use common\msg\UserMsg;
use yii\base\Exception;

class WapUserCard {

    //用户id
    public $userID;
    /**
     * @param array $userID 用户id
     */
    public function __construct($userID = null){
        if($userID)
            $this->userID = $userID;
    }

    /**
     * @param $parame充值提供参数
     * @return bool
     */
    public function deal($parame, $source = 1, $_return_url = ''){
        $parame['name_goods'] = '充值';
        $userID = $this->userID;
        $return['status'] = 0;
        $return['msg'] = UserMsg::$time_out;
        if($parame['money_order'] <= 0){
            $return['msg'] = '充值金额不能小于0元。';
            return $return;
        }
        //获取银行卡号
        if( isset($parame['bank_code'])){
            $cardInfo = \common\models\DAO\UserCard::findOne(array('userID'=>$userID,'id'=>CommonFunction::decrypt($parame['bank_code'])));
            if(!$cardInfo)
                return $return;
            $cardInfo = $cardInfo->attributes;
            if(!$cardInfo['card'])
                return $return;
            if($cardInfo['no_agree'])
                $parame['no_agree'] = CommonFunction::decrypt($cardInfo['no_agree'], CommonVar::$encrypt);
            $parame['card_no'] = CommonFunction::decrypt($cardInfo['card'], CommonVar::$encrypt);
        }
        $encrypt = CommonVar::$encrypt;
        $userModel = User::findOne($userID);
        $userInfo = $userModel->attributes;
        //商户订单号
        $no_order = CommonFunction::buildOrder();
        //商户网站订单系统中唯一订单号，必填
        $now = time();
        $transaction = \Yii::$app->db->beginTransaction();
        try{
            //系统添加订单
            $userCharge = new UserCharge();
            $userCharge->userID = $userID;
            $userCharge->createTime = $now;
            $userCharge->sourceID = $source;
            $userCharge->money = doubleval($parame['money_order']) * 100;
            $userCharge->card = CommonFunction::encrypt($parame['card_no'], $encrypt);;
            $userCharge->order = $no_order;
            $charge_result = $userCharge->save();
            if(!$charge_result){
                $transaction->rollBack();
                return $return;
            }
            if(!$userInfo['identity'] || !$userInfo['realName']){
                if(!isset($parame['id_no']) || !isset($parame['acct_name'])){
                    $return['msg'] = UserMsg::$no_name_card;
                    return $return;
                }else if(strstr($parame['id_no'], 'X'))
                    $parame['id_no'] = strtolower($parame['id_no']);
                $identity = CommonFunction::encrypt($parame['id_no'], $encrypt);
                //验证身份证是否已经被使用
                $is_reg = UserIdentity::find()->where(array('identity'=>$identity))->andFilterWhere(['!=', 'userID', $userID])->all();
                if($is_reg){
                    $return['msg'] = UserMsg::$use_card;
                    return $return;
                }
                //身份认证
                $identityModel = new UserIdentity();
                $identityModel->userID = $userID;
                $identityModel->identity = $identity;
                $identityModel->realName = $parame['acct_name'];
                $identityModel->orderID = $userCharge->id;
                $identity_result = $identityModel->save();
                if(!$identity_result){
                    $transaction->rollBack();
                    return $return;
                }
            }else{
                $parame['id_no'] = CommonFunction::decrypt($userInfo['identity'], CommonVar::$encrypt);
                $parame['acct_name'] = $userInfo['realName'];
            }
            $transaction->commit();
        }catch (Exception $e){
            $transaction->rollBack();
            return $return;
        }
        /**************************请求参数 start**************************/
        //商户用户唯一编号
        $user_id = CommonFunction::encrypt('scyd'.$userID, CommonVar::$encrypt);

        //支付类型
        $busi_partner = LLpayConfig::$busi_partner;


        //付款金额
        $money_order = $parame['money_order'];
        //必填

        //商品名称
        $name_goods = $parame['name_goods'];

        //卡号
        $card_no = $parame['card_no'];

        //姓名
        $acct_name = $parame['acct_name'];

        //身份证号
        $id_no = $parame['id_no'];

        //{"frms_ware_category":"2009","user_info_mercht_userno":"13165753886","user_info_dt_register":"20150605122130",
        //"user_info_full_name":"张逢春","user_info_id_no":"610303198602124816","user_info_identify_state":0,"user_info_identify_type":1}
        //风险控制参数
        $risk_item = '{\"frms_ware_category\":\"2009\",\"user_info_mercht_userno\":\"'.$user_id.'\",\"user_info_dt_register\":\"'.date('YmdHis',$userInfo['createTime']).'\",\"user_info_full_name\":\"'.$parame['acct_name'].'\",\"user_info_id_no\":\"'.$parame['id_no'] .'\",\"user_info_identify_state\":0,\"user_info_identify_type\":1}';

        //$risk_item = '{"user_info_bind_phone":"13958069593","user_info_dt_register":"20131030122130","risk_state":"1","frms_ware_category":"1009"}';
        //服务器异步通知页面路径
        $notify_url = LLpayWapConfig::$notify_url;
        //需http://格式的完整路径，不能加?id=123这类自定义参数
        //页面跳转同步通知页面路径
        $return_url = LLpayWapConfig::$return_url;
        $_return_url && $return_url = $_return_url;
        //需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/

        /**************************请求参数 end**************************/

        date_default_timezone_set('PRC');
        $llpay_config = LLpayWapConfig::getConfig();
        //构造要请求的参数数组，无需改动
        $parameter = array (
            "oid_partner" => trim($llpay_config['oid_partner']),
            "app_request" => trim($llpay_config['app_request']),
            "sign_type" => trim($llpay_config['sign_type']),
            "valid_order" => trim($llpay_config['valid_order']),
            "user_id" => $user_id,
            "busi_partner" => $busi_partner,
            "no_order" => $no_order,
            "dt_order" => date('YmdHis', $now),
            "name_goods" => $name_goods,
            "money_order" => $money_order,
            "notify_url" => $notify_url,
            "url_return" => $return_url,
            "card_no" => $card_no,
            "acct_name" => $acct_name,
            "id_no" => $id_no,
            "risk_item" => $risk_item,
        );
        //协议号
        if(isset($parame['no_agree'])){
            $parameter['no_agree'] = $parame['no_agree'];
        }
        header("Content-type: text/html; charset=utf-8");
        $llpaySubmit = new LLpayWapSubmit($llpay_config);
        //建立请求
        if($source == 3)
            $html_text = $llpaySubmit->appBuildRequestForm($parameter, "post", "确认");
        else
            $html_text = $llpaySubmit->buildRequestForm($parameter, "post", "确认");
        $return['status'] = 1;
        $return['data'] = $html_text;
        unset($return['msg']);
        return $return;
    }

}